package com.study.designmodel;

/**
 * @description: FactoryModel    工厂模式  ioc举例
 * @date: 2020/11/20 1:29
 * @author: hcm
 * @version: 1.0
 */
public class FactoryModel {
    public static void main(String[] args) {
        Fruit instance = Factory.getInstance("com.study.designmodel.Apple");
        if(instance!=null){
            instance.eat();
        }
    }
}

/**
 * 水果总接口
 */
interface Fruit{
    /**
     * 水果的用途
     */
    void eat();
}

/**
 * 然后就很有必要有实现类来实现接口，比如各种水果
 */
class Orange implements Fruit{


    @Override
    public void eat() {
        System.out.println("烂橘子开吃");
    }
}

class Apple implements Fruit{

    @Override
    public void eat() {
        System.out.println("烂苹果开吃");
    }
}
/**
 * 然后就是反射获取实例的工厂类
 */
class Factory{
    /**
     * 获取水果实例
     * @param className
     * @return
     */
    public static Fruit getInstance(String className){

        /**
         * 动态获取
         */
        Fruit fruit = null;
        /**
         * 反射
         */
        try {
            fruit = (Fruit) Class.forName(className).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return fruit;
    }
}